﻿package com.saint.utils
{
	import com.saint.utils.events.ImageLoaderEvent;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author ...
	 */
	public class ImageLoader extends Sprite
	{
		
		private var image:Loader
		
		/**
		 * CONSTRUCTOR
		 *
		 * load image designated in the imagePath arguement
		 *
		 * @param	imagePath
		 */
		public function ImageLoader(imagePath:String = undefined)
		{
			if (imagePath != "undefined")
			{
				
				var imageURL:URLRequest = new URLRequest(imagePath);
				image = new Loader();
				
				image.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
				image.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
				image.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler,false, 0, true);
				image.contentLoaderInfo.addEventListener(Event.INIT, initHandler,false, 0, true);
				image.contentLoaderInfo.addEventListener(Event.OPEN, openHandler,false, 0, true);
				image.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler,false, 0, true);
				image.contentLoaderInfo.addEventListener(Event.UNLOAD, unLoadHandler, false, 0, true);
				
				image.load(imageURL);
				trace("ImageLoader - loading " + imagePath);
			}
			else
			{
				dispatchEvent(new ImageLoaderEvent(ImageLoaderEvent.LOAD_ERROR));
			}
			
		}
		
		
	
        private function ioErrorHandler(event:IOErrorEvent):void
		{
            trace("ImageLoader.ioErrorHandler: " + event);
			removeListeners()
        }

		private function completeHandler(event:Event):void
		{
            trace("ImageLoader.completeHandler: " + event);
			addChild(image);
			removeListeners();
        }
	

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + event);
        }

        private function initHandler(event:Event):void {
            trace("initHandler: " + event);
        }


        private function openHandler(event:Event):void {
            trace("openHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
        }

        private function unLoadHandler(event:Event):void {
            trace("unLoadHandler: " + event);
        }
		
		
		private function removeListeners():void
		{
				image.removeEventListener(Event.COMPLETE, completeHandler);
				image.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
	}
	
}